$(document).ready(function(){
	buildNav();
	$('#manual').bind("click", function() {instant.sort()});
	$('ul#instantSize li').bind("click", function() {instant.setSize(this)});
	instant.init();
});

var parentURL = "http://121.40.113.140:8983/solr/core-http/";

var source = new HashMap();
//source.put(1,1);
var currPage = 1;
var docsPerPage = 30;
var docs = [];

var instant = {
	init: function(mode, keyword){
		autoReload.init();
		autoReload.setAuto(false);

		$("#loading").removeClass("hidden");
		var reqParams = source.keys();
		var start = (currPage - 1) * docsPerPage;
		var url = "";
		if (mode == 3) {
			var value = keywords.get(keyword);
			var qStr = value.join("+title%3A");
			url = parentURL + "select/?q=+title%3A" + qStr + "&sort=datetime%20desc&version=2.2&start=" + start + "&rows=" + docsPerPage + "&indent=on&wt=json&json.wrf=?";
		} else {
			url = parentURL + "select/?q=*%3A*&sort=datetime%20desc&version=2.2&start=" + start + "&rows=" + docsPerPage + "&indent=on&wt=json&json.wrf=?";
			if (reqParams.length > 0) {
				url = parentURL + "select/?q=source%3A%28" + reqParams.join("+") + "%29&sort=datetime%20desc&version=2.2&start=" + start + "&rows=" + docsPerPage + "&indent=on&wt=json&json.wrf=?";
			}
		}
		$.getJSON(url, function(data) {
			docs = data.response.docs;
	        var output='<div class="cnt"><span class="blank15"></span><ul class="list_txt">';
			for(var i=0; i<docs.length; i++) {
				var content = "<font color='#FF0000'>未采集到正文</font>";
				var contentAnchor = "";
				if (docs[i].content) {
					content = "<pre>" + docs[i].content + "</pre>";
					contentAnchor = '<i class="icon content"></i>';
				}
	            output += '<li><span class="right f12px cDGray">' + docs[i].datetime.replace("T", " ").replace("Z", "") + 
						  '</span><a href="#" onClick="javascript:forceJump(\'statistic.html#source=' + docs[i].source + '\')" class="cBlue">[' + docs[i].source + ']</a>' +
						  '<a href="' + docs[i].url + '" target="_blank">' + docs[i].title + '</a>' +
						  ' - <span>' + contentAnchor + '<i class="icon comment"></i></span>' + 
						  '</li><span class="detail hidden">' + content + '</span>';
				if ((i + 1) % 5 == 0) {
					output += '</ul><span class="blank15"></span><ul class="list_txt">';
				}
			}
			output += '</ul></div>';
			
			//add space line
			output += '<span class="hr_dot"></span> <span class="blank15"></span>';

			//add bar_pages
			var totalDocs = parseInt(data.response.numFound);
			var pages = totalDocs / docsPerPage;
			var numPages = pages > 10 ? 10 : pages;
			var prevUrl = nextUrl = "";
			if (currPage > 1) {
				prevUrl = parentURL + 'query/#page=' + (currPage - 1);
			}
			if (currPage < numPages) {
				nextUrl = parentURL + 'query/#page=' + (currPage + 1);
			}
			output += '<div class="bar_pages">';
			if (prevUrl.length > 0) {
				output += '<a href="' + prevUrl+ '" class="bar_pages_flip">上一页</a>';
			} else {
				output += '<span class="bar_pages_flip">上一页</span>';
			}
			for (var i=0; i<numPages; i++) {
				var page = i+1;
				var pageUrl = parentURL + 'query/#page=' + page;
				if (page == currPage) {
					output += '<span class="active">' + page + '</span>';
				} else {
					output += '<a href="' + pageUrl+ '">' + page + '</a>'
				}
			}
			if (nextUrl.length > 0) {
				output += '<a href="' + nextUrl+ '" class="bar_pages_flip">下一页</a>';
			} else {
				output += '<span class="bar_pages_flip">下一页</span>';
			}
			output += '</div> <span class="blank15"></span>';
			$("#loading").addClass("hidden");
			$("#instantPanel").html(output);

			$("span i.content").click(function(){
				$(this).parent().parent().next().slideToggle();
				autoReload.clickCheck();
				if (autoReload.auto) {
					$("#reloadSwitch").addClass("btn_checked");
				} else {
					$("#reloadSwitch").removeClass("btn_checked");
				}				
			});

			$("div.bar_pages a").die().live("click",function(){
				instant.showPage(this.href);
			});
		});
		instant.flushNav();
	},
	flushNav: function() {
		var url = parentURL + "select/?q=*%3A*&rows=0&facet=true&facet.field=source&facet.limit=-1&wt=json&json.wrf=?";
		$.getJSON(url, function(data) {
			$("#instantHolder").empty();
			$('<li id="allitems">全部</li>').click(function(){
				$(this).toggleClass("active");
				instant.updateOther();
			}).appendTo($("#instantHolder"));
			var groups = data.facet_counts.facet_fields.source;
			var allitems = 0;
			for(var i=0; i<groups.length; i+=2) {
				//var source = data.groups[i].source;
				allitems += groups[i+1];
	            $('<li id="' + groups[i] + '">' + groups[i] + '(' + groups[i+1] + ')' + '</li>').click(function(){
						//alert(this.innerHTML);
						$(this).toggleClass("active");
						instant.updateMaster();
				}).appendTo($("#instantHolder"));

				var detailUrl = parentURL + "select/?q=+source%3A" + groups[i] + "&sort=datetime%20desc&version=2.2&start=0&rows=1&indent=on&wt=json&json.wrf=?";
				$.getJSON(detailUrl, function(detailData) {
					docs = detailData.response.docs;

					var output = "";
					if (docs.length > 0) {
		
						var timeStr = docs[0].datetime.replace("T", " ").replace("Z", "");

						output = '<span class="right f12px cDGray">' + timeStr + '</span>'
	
			            $(output).appendTo($("#" + docs[0].source));
			            $("#" + docs[0].source).attr("data-val", timeStr);
					}
				});
			}
			$('#allitems').html("全部(" + allitems + ')').attr("data-val", "2100-01-01 00:00:00");
			instant.update();
			$("#loading").addClass("hidden");
		});
	},
	updateMaster: function() {
		var x = $("#instantHolder li:gt(0)").toArray();
		for (var i=0; i<x.length; i++) {
			if ($(x[i]).hasClass("active")) {
				$("#instantHolder li:eq(0)").removeClass("active");
			}
		}
		instant.scanNav();
	},
	updateOther: function(){
		if ($("#instantHolder li:eq(0)").hasClass("active")) {
			var x = $("#instantHolder li:gt(0)").toArray();
			for (var i=0; i<x.length; i++) {
				$(x[i]).removeClass("active");
			}
		}
		instant.scanNav();
	},
	update: function() {
		if (source.size() == 0)	{
			$("#instantHolder li:eq(0)").addClass("active");
			instant.updateOther();
		} else {
			var values = source.values();
			for (var i=0; i<values.length; i++) {
				$("#instantHolder li:eq(" + values[i] + ")").addClass("active");
			}
			instant.updateMaster();
		}
		$("#instantHolder li:odd").addClass("odd");
	},
	scanNav: function() {
		source.clear();
		var x = $("#instantHolder li:gt(0)").toArray();
		for (var i=0; i<x.length; i++) {
			if ($(x[i]).hasClass("active")) {
				var strArray = x[i].innerHTML.split("(");
				source.put(strArray[0], i+1);
				//alert(source.size());
			}
		}
		//alert("update source " + source.size());
	},
	setSize: function(obj) {
		var value = $(obj).text();
		docsPerPage = parseInt(value.substring(0, value.length - 1));
		//docsPerPage = 60;
		if (!$(obj).hasClass("active")) {
			$(obj).siblings(".active").toggleClass("active");
			$(obj).addClass("active");
			instant.init();
		}
	},
	getPage: function(url){
		var matchs = url.match(/#([^&]*&)*page=([^&]+)/i);
		page = matchs ? parseInt(matchs[2]) : 1;
		return page;
	},
	showPage: function(url) {
		currPage = instant.getPage(url);
		instant.init();
	},
	sort: function() {
		var aLi = $("#instantHolder li");
		var arr = [];
		for(var i=0;i<aLi.length;i++)
		{
			arr.push(aLi[i]);
		}
		arr.sort(function(a,b){
			var aTime = $(a).attr('data-val');
			var bTime = $(b).attr('data-val');

			var start = new Date(aTime.replace("-", "/").replace("-", "/"));
			var end   = new Date(bTime.replace("-", "/").replace("-", "/"));		
			return start - end;
		});
		$("#instantHolder").empty();
		for(var i=0;i<arr.length;i++)
		{
			$("#instantHolder").append(arr[i]);
		}
		$("#instantHolder li").removeClass("odd");
		$("#instantHolder li:odd").addClass("odd");		
	}
};
